﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MakeIT.MiraPark.Negocios;

namespace MiraPark
{
    public partial class FormCadastroTabelaAvulso : Form
    {
        private string operacao = "";

        public FormCadastroTabelaAvulso()
        {
            InitializeComponent();

        }

        private void FormCadastroTabelaAvulso_Load(object sender, EventArgs e)
        {
            //Popular a lista de tabelaAvulsos cadastrados
            this.dataGridViewTabelaAvulso.DataSource = ModelBO.getTabelaAvulsos();
            this.comboBoxHorario.DataSource = ModelBO.getHorarios(TipoPeriodoVO.TipoPeriodo.Avulso);


            setupButtonsControls();
        }

        private void dataGridViewTabelaAvulso_SelectionChanged(object sender, EventArgs e)
        {
            setupButtonsControls();
        }

        private void buttonNovo_Click(object sender, EventArgs e)
        {
            this.operacao = "novo";

            this.dateTimePickerInicioVigencia.Value = DateTime.Today;
            this.dateTimePickerFimVigencia.Value = DateTime.Today;
            setupButtonsControls();
        }

        private void buttonCancelar_Click(object sender, EventArgs e)
        {
            this.operacao = "cancelar";
            setupButtonsControls();
        }

        private void buttonEditar_Click(object sender, EventArgs e)
        {
            this.operacao = "editar";
            setupButtonsControls();
        }

        private void buttonExcluir_Click(object sender, EventArgs e)
        {
            this.operacao = "excluir";

            List<TabelaAvulsoVO> tabelaAvulsoList = (List<TabelaAvulsoVO>)this.dataGridViewTabelaAvulso.DataSource;
            TabelaAvulsoVO tabelaAvulsoVO = tabelaAvulsoList[this.dataGridViewTabelaAvulso.CurrentRow.Index];
            DialogResult dr = MessageBox.Show(this, "Confirma a exclusão da tabela " + tabelaAvulsoVO.tabelaAvulso, "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr.ToString().Equals("Yes"))
            {
                ModelBO.getTabelaAvulsoXPeriodos(tabelaAvulsoVO);
                ModelBO.delTabelaAvulsoXPeriodos(tabelaAvulsoVO.tabelaAvulsoPVOs);
                
                ModelBO.delTabelaAvulso(tabelaAvulsoVO);

                int nRow = this.dataGridViewTabelaAvulso.CurrentRow.Index;
                this.dataGridViewTabelaAvulso.DataSource = ModelBO.getTabelaAvulsos();
                if (this.dataGridViewTabelaAvulso.Rows.Count > 0)
                {
                    dataGridViewTabelaAvulso.CurrentCell = dataGridViewTabelaAvulso.Rows[Math.Min(nRow, this.dataGridViewTabelaAvulso.Rows.Count - 1)].Cells[3];
                    dataGridViewTabelaAvulso.Rows[Math.Min(nRow, this.dataGridViewTabelaAvulso.Rows.Count - 1)].Selected = true;
                }

                setupButtonsControls();
            }
        }

        private void buttonSalvar_Click(object sender, EventArgs e)
        {
            String erros = "";
            if (this.textBoxTabelaAvulso.Text.Trim().Length == 0)
                erros = erros + "Controle deve ser informado.\r\n";
            if (this.comboBoxHorario.SelectedItem==null)
                erros = erros + "Controle de horário deve ser informado.\r\n";
            if (this.dateTimePickerInicioVigencia.Value > this.dateTimePickerFimVigencia.Value)
                erros = erros + "Vigência inicial MAIOR que vigência final. (Segunda)\r\n";
            if (erros.Length > 0)
            {
                MessageBox.Show(this, erros, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            TabelaAvulsoVO tabelaAvulso = null;

            if (this.operacao.Equals("novo"))
            {
                tabelaAvulso = TabelaAvulsoVO.CreateTabelaAvulsoVO();
                tabelaAvulso.idHorario = int.Parse(this.comboBoxHorario.SelectedValue.ToString());
                tabelaAvulso.idTabelaAvulso = (int)ModelBO.newTabelaAvulso(tabelaAvulso);
            }
            if (this.operacao.Equals("editar"))
            {
                List<TabelaAvulsoVO> tabelaAvulsoList = (List<TabelaAvulsoVO>)this.dataGridViewTabelaAvulso.DataSource;
                tabelaAvulso = tabelaAvulsoList[this.dataGridViewTabelaAvulso.CurrentRow.Index];
            }

            tabelaAvulso.idHorario = int.Parse(this.comboBoxHorario.SelectedValue.ToString());
            tabelaAvulso.tabelaAvulso = this.textBoxTabelaAvulso.Text;
            tabelaAvulso.inicioVigencia = this.dateTimePickerInicioVigencia.Value;
            tabelaAvulso.fimVigencia = this.dateTimePickerFimVigencia.Value;
            tabelaAvulso.segunda = checkBoxSegunda.Checked;
            tabelaAvulso.terca = checkBoxTerca.Checked;
            tabelaAvulso.quarta = checkBoxQuarta.Checked;
            tabelaAvulso.quinta = checkBoxQuinta.Checked;
            tabelaAvulso.sexta = checkBoxSexta.Checked;
            tabelaAvulso.sabado = checkBoxSabado.Checked;
            tabelaAvulso.domingo = checkBoxDomingo.Checked;
            tabelaAvulso.feriados = checkBoxFeriado.Checked;
            tabelaAvulso.outrasDatas = checkBoxOutraDAta.Checked;
            tabelaAvulso.diaria = this.numericUpDownDiaria.Value;
            tabelaAvulso.diariaEspecial = this.numericUpDownDiariaEspecial.Value;

            ModelBO.setTabelaAvulso(tabelaAvulso);

            //salvar periodos
            List<TabelaAvulsoPVO> listaTabelaAvulsoPVO = new List<TabelaAvulsoPVO>();
            foreach (DataGridViewRow dgvRow in dataGridViewPeriodos.Rows)
            {
                int minutos = 0;
                decimal valor = 0.0M;
                try{minutos=int.Parse(dgvRow.Cells["minutos"].Value.ToString());} catch(Exception ex){}
                try{valor=decimal.Parse(dgvRow.Cells["valor"].Value.ToString());} catch(Exception ex){}

                TabelaAvulsoPVO tabelaAvulsoPVO = TabelaAvulsoPVO.CreateTabelaAvulsoPVO();
                tabelaAvulsoPVO.idTabelaAvulsoP = (int)dgvRow.Cells["periodo"].Value;
                tabelaAvulsoPVO.idTabelaAvulso = tabelaAvulso.idTabelaAvulso;
                tabelaAvulsoPVO.minutos = minutos;
                tabelaAvulsoPVO.valor = valor;
                tabelaAvulsoPVO.acumula = (bool)dgvRow.Cells["acumula"].Value;
                listaTabelaAvulsoPVO.Add(tabelaAvulsoPVO);
            }
            ModelBO.getTabelaAvulsoXPeriodos(tabelaAvulso);
            ModelBO.delTabelaAvulsoXPeriodos(tabelaAvulso.tabelaAvulsoPVOs);
            ModelBO.newTabelaAvulsoXPeriodos(listaTabelaAvulsoPVO);


            this.operacao = "salvar";

            List<TabelaAvulsoVO> listTabelaAvulsoVOs = ModelBO.getTabelaAvulsos();
            dataGridViewTabelaAvulso.DataSource = listTabelaAvulsoVOs;
            int nRow = listTabelaAvulsoVOs.FindIndex(a => a.idTabelaAvulso == tabelaAvulso.idTabelaAvulso);
            dataGridViewTabelaAvulso.CurrentCell = dataGridViewTabelaAvulso.Rows[nRow].Cells[3];
            dataGridViewTabelaAvulso.Rows[nRow].Selected = true;

            setupButtonsControls();
        }


        private void setupButtonsControls()
        {
            bool haRows = this.dataGridViewTabelaAvulso.Rows.Count > 0 && this.dataGridViewTabelaAvulso.CurrentRow!=null;
            bool novo = this.operacao.Equals("novo");
            bool edit = this.operacao.Equals("editar");
            bool canc = this.operacao.Equals("cancelar");

            this.buttonCancelar.Enabled = novo || edit;
            this.buttonNovo.Enabled = !novo && !edit;
            this.buttonEditar.Enabled = haRows && !novo && !edit;
            this.buttonExcluir.Enabled = haRows && !novo && !edit;
            this.buttonSalvar.Enabled = novo || edit;

            this.comboBoxHorario.Enabled = novo || edit;
            this.textBoxTabelaAvulso.Enabled = novo || edit;
            this.dateTimePickerInicioVigencia.Enabled = novo || edit;
            this.dateTimePickerFimVigencia.Enabled = novo || edit;
            this.checkBoxSegunda.Enabled = novo || edit;
            this.checkBoxTerca.Enabled = novo || edit;
            this.checkBoxQuarta.Enabled = novo || edit;
            this.checkBoxQuinta.Enabled = novo || edit;
            this.checkBoxSexta.Enabled = novo || edit;
            this.checkBoxSabado.Enabled = novo || edit;
            this.checkBoxDomingo.Enabled = novo || edit;
            this.checkBoxFeriado.Enabled = novo || edit;
            this.checkBoxOutraDAta.Enabled = novo || edit;
            this.numericUpDownDiaria.Enabled = novo || edit;
            this.numericUpDownDiariaEspecial.Enabled = novo || edit;

            this.dataGridViewTabelaAvulso.Enabled = !novo && !edit;

            this.dataGridViewPeriodos.Enabled = novo || edit;
            this.dataGridViewPeriodos.ReadOnly = !novo && !edit;
            this.dataGridViewPeriodos.Columns[1].ReadOnly = true;
            this.buttonIncluirPeriodo.Enabled = novo || edit;

            if (!haRows || novo)
            {
                this.textBoxTabelaAvulso.Text = "";

                this.dataGridViewPeriodos.Rows.Clear();
            }
            else {
                List<TabelaAvulsoVO> tabelaAvulsoList = (List<TabelaAvulsoVO>)this.dataGridViewTabelaAvulso.DataSource;
                TabelaAvulsoVO tabelaAvulso = tabelaAvulsoList[this.dataGridViewTabelaAvulso.CurrentRow.Index];
                this.textBoxID.Text = tabelaAvulso.idTabelaAvulso.ToString();
                this.comboBoxHorario.SelectedValue = tabelaAvulso.idHorario;
                this.textBoxTabelaAvulso.Text = tabelaAvulso.tabelaAvulso;
                this.dateTimePickerInicioVigencia.Value = tabelaAvulso.inicioVigencia;
                this.dateTimePickerFimVigencia.Value = tabelaAvulso.fimVigencia;
                this.checkBoxSegunda.Checked = tabelaAvulso.segunda;
                this.checkBoxTerca.Checked = tabelaAvulso.terca;
                this.checkBoxQuarta.Checked = tabelaAvulso.quarta;
                this.checkBoxQuinta.Checked = tabelaAvulso.quinta;
                this.checkBoxSexta.Checked = tabelaAvulso.sexta;
                this.checkBoxSabado.Checked = tabelaAvulso.sabado;
                this.checkBoxDomingo.Checked = tabelaAvulso.domingo;
                this.checkBoxFeriado.Checked = tabelaAvulso.feriados;
                this.checkBoxOutraDAta.Checked = tabelaAvulso.outrasDatas;
                this.numericUpDownDiaria.Value = tabelaAvulso.diaria;
                this.numericUpDownDiariaEspecial.Value = tabelaAvulso.diariaEspecial;

                ModelBO.getTabelaAvulsoXPeriodos(tabelaAvulso);
                this.dataGridViewPeriodos.Rows.Clear();
                foreach (TabelaAvulsoPVO tabelaAvulsoPVO in tabelaAvulso.tabelaAvulsoPVOs)
                {
                    int nrow = this.dataGridViewPeriodos.Rows.Add();
                    DataGridViewRow dgvRow = dataGridViewPeriodos.Rows[nrow];
                    dgvRow.Cells["periodo"].Value = tabelaAvulsoPVO.idTabelaAvulsoP;
                    dgvRow.Cells["minutos"].Value = tabelaAvulsoPVO.minutos;
                    dgvRow.Cells["valor"].Value = tabelaAvulsoPVO.valor;
                    dgvRow.Cells["acumula"].Value = tabelaAvulsoPVO.acumula;
                }
            }
            if (novo || edit){
                this.textBoxTabelaAvulso.Focus();
            }
        }

        private void dataGridViewTabelaAvulso_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            foreach (DataGridViewRow dgvr in dgv.Rows)
            {
                HorarioVO hvo = (HorarioVO)dgvr.Cells["horarioVO"].Value;
                dgvr.Cells["controle"].Value = hvo.controle;
            }

        }

        private void buttonIncluirPeriodo_Click(object sender, EventArgs e)
        {
            int rownum = this.dataGridViewPeriodos.Rows.Add();
            DataGridViewRow dgvrow = dataGridViewPeriodos.Rows[rownum];
            dgvrow.Cells["periodo"].Value = rownum + 1;
            dgvrow.Cells["minutos"].Value = 0;
            dgvrow.Cells["valor"].Value = 0.00M;
            dgvrow.Cells["acumula"].Value = false;
        }

        private void dataGridViewPeriodos_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                if (this.dataGridViewPeriodos.Columns[e.ColumnIndex].Name.Equals("buttonExcluirPeriodo"))
                {
                    DialogResult dr = MessageBox.Show(this, "Confirma a exclusão do periodo " + (e.RowIndex+1), "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr.ToString().Equals("Yes"))
                    {
                        int rownum = 1;
                        dataGridViewPeriodos.Rows.RemoveAt(e.RowIndex);
                        foreach (DataGridViewRow dgvRow in dataGridViewPeriodos.Rows)
                        {
                            dgvRow.Cells["periodo"].Value = rownum++;
                        }
                    }
                }
            }
        }

        private void buttonListagem_Click(object sender, EventArgs e)
        {
            FormReportTabelaAvulso formx = new FormReportTabelaAvulso();
            formx.MdiParent = this.MdiParent;
            formx.Show();
        }
    }
}
